package quenue;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class ShareDate {//资源类
    private int number = 0;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void increment() throws Exception {
        //1、判断
        lock.lock();
        try {
            while (number != 0) {
                condition.await();
            }
            //干活
            number++;
            System.out.println(Thread.currentThread().getName() + "\t" + number);
            //通话唤醒
            condition.signal();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

    public void decrement() throws Exception {
        //1、判断
        lock.lock();
        try {
            while (number == 0) {
                condition.await();
            }
            //干活
            number--;
            System.out.println(Thread.currentThread().getName() + "\t" + number);
            //通话唤醒
            condition.signal();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }



}
/*
题目：一个初始值为零的变量，两个线程对其交替操作，一个加一，一个减1，进行五轮。
1、线程  操作  资源类
2、判断 干活   通知
3、防止虚假线程唤醒，用while循环
 */
public class ProdConsumer_Tradition {

    public static void main(String[] args) {

        ShareDate shareDate = new ShareDate();

            new Thread(() -> {
                    //线程要执行的代码
                for (int i = 1; i <= 5 ; i++) {
                    try {
                        shareDate.increment();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                 },"AAAA").start();

        new Thread(() -> {
            //线程要执行的代码
            for (int i = 1; i <= 5 ; i++) {
                try {
                    shareDate.decrement();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        },"BBBB").start();

    }
}
